package com.winit.openapi.ums.controller;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.CheckCodeCommand;
import com.winit.ums.spi.commnad.CustomerServiceCommand;
import com.winit.ums.spi.commnad.IdCommand;
import com.winit.ums.spi.commnad.customer.BatchAuditCommand;
import com.winit.ums.spi.commnad.customer.CustomerIsOpenAgreementForDsw;
import com.winit.ums.spi.commnad.customer.CustomerQueryCommand;
import com.winit.ums.spi.commnad.customer.GetDirectShipmentWhitelistCommand;
import com.winit.ums.spi.commnad.customer.SenderAddressCommand;
import com.winit.ums.spi.commnad.customer.agreement.QueryCustomerAgreementByTypeAndCustomerCode;
import com.winit.ums.spi.contract.ContractAgreementManagerService;
import com.winit.ums.spi.contract.ContractAgreementTemplateService;
import com.winit.ums.spi.contract.FileSendManagerService;
import com.winit.ums.spi.contract.command.AlertPageCheckCommand;
import com.winit.ums.spi.contract.command.CheckCustomerServiceCommand;
import com.winit.ums.spi.contract.command.SignContractCommand;
import com.winit.ums.spi.contract.vo.ContractManagerVo;
import com.winit.ums.spi.contract.vo.ServiceTypeVo;
import com.winit.ums.spi.contract.vo.TemplatePathVo;
import com.winit.ums.spi.customer.DirectShipmentWhitelistService;
import com.winit.ums.spi.customer.command.OpeningServiceCommand;
import com.winit.ums.spi.customer.command.QueryDswByCustomerCodeCommand;
import com.winit.ums.spi.customer.vo.CompanyVo;
import com.winit.ums.spi.customer.vo.DirectShipmentWhitelistVo;
import com.winit.ums.spi.vo.customer.Contract;

/**
 * 开通合同，协议共用Controller
 * @author qibin.tang
 *
 */
@Controller
@RequestMapping(value = "/customerService")
public class CustomerServiceController extends BaseController {
	
	@Resource
    private UmsCustomerService umsCustomerService;
	
	@Resource
	private ContractAgreementManagerService contractAgreementManagerService;
	
	@Resource
	private ContractAgreementTemplateService contractAgreementTemplateService;
	
	@Resource
	private FileSendManagerService  fileSendManagerService;
	
	@Resource
	private DirectShipmentWhitelistService directShipmentWhitelistService;
	
	/**
     * 开通ISP权限
     * 
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/openingIspService")
    public String openingIspService(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	CustomerServiceCommand command = JSON.parseObject(requestMsg.getData().toString(),CustomerServiceCommand.class);
    	command.setCtx(CommandContext.getContext());
    	umsCustomerService.openingIspService(command);
        return SUCCESS;
    }
    
    /**
     * 开通海外仓权限
     * 
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/openingOwhsService")
    public String openingOwhsService(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	CommandContext ctx = CommandContext.getContext();
        String userName = ctx.getUsername();       
        Map<String,Object> data = umsCustomerService.openingOwhsService(userName);
        responseMsg.setData(data);
        return SUCCESS;
    }
    @RequestMapping(value = "/uploadCertificate")
    public String uploadCertificate(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {           
        CustomerServiceCommand command = new CustomerServiceCommand();
        command = JSON.parseObject(requestMsg.getData().toString(),CustomerServiceCommand.class);
        command.setCtx(CommandContext.getContext());
        Map<String,Object> data = umsCustomerService.uploadCertificate(command);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/batchAuditMaterials")
    public String batchAuditMaterials(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {           
        BatchAuditCommand command = new BatchAuditCommand();
        command = JSON.parseObject(requestMsg.getData().toString(),BatchAuditCommand.class);
        command.setCtx(CommandContext.getContext());
        umsCustomerService.batchAuditMaterials(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("flag", "true");
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 查询寄件地址
     * 
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/querySenderAddress")
    public String querySenderAddress(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        CommandContext ctx = CommandContext.getContext();
        String userName = ctx.getUsername();       
        CompanyVo companyVo = umsCustomerService.querySenderAddress(userName);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("companyVo", companyVo);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 修改合同寄件地址
     * 
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/modifySenderAddress")
    public String modifySenderAddress(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        CommandContext ctx = CommandContext.getContext();
        String userName = ctx.getUsername();     
        SenderAddressCommand addressCommand = JSON.parseObject(requestMsg.getData().toString(),SenderAddressCommand.class);
        addressCommand.setUserName(userName);
        //不是线下签署
        if("N".equals(addressCommand.getIsOfflineSigned())||StringUtils.isBlank(addressCommand.getIsOfflineSigned())){                    
            umsCustomerService.modifySenderAddress(addressCommand); 
        }else{
            umsCustomerService.modifyWithOfflineSigned(addressCommand); 
        }
        //处理寄件数据,并生成清关协议合同
        fileSendManagerService.initFileSendManager(addressCommand);
        
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("flag", true);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 开通退货服务
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/openingReturnGoodsService")
    public String openingReturnGoodsService(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	OpeningServiceCommand command = JSON.parseObject(requestMsg.getData().toString(),OpeningServiceCommand.class);
    	command.setCtx(CommandContext.getContext());
    	command.setCustomerName(CommandContext.getContext().getUsername());
    	umsCustomerService.openingReturnGoodsService(command);
        return SUCCESS;
    }
    
    /**
     * 是否生成合同
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/isCreateContract")
    public String isCreateContract(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	OpeningServiceCommand command = new OpeningServiceCommand();
    	command.setCtx(CommandContext.getContext());
    	command.setCustomerName(CommandContext.getContext().getUsername());
    	boolean bool = umsCustomerService.isCreateContract(command);
        Map<String, Boolean> data = new HashMap<String, Boolean>();
        data.put("isCreateContract", bool);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    
    /**
     * 根据服务类型与客户编码判断客户是否同意该服务类型（服务类型包含合同与协议）true:已同意，false:未同意
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/checkCustomerService")
    public String checkCustomerService(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	CheckCustomerServiceCommand command = JSON.parseObject(requestMsg.getData().toString(),CheckCustomerServiceCommand.class);
    	command.setCtx(CommandContext.getContext());
    	TemplatePathVo templatePathVo = contractAgreementManagerService.checkCustomerService(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("templatePath", templatePathVo);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    
    /**
     * 客户登录后判断是否需要弹窗，只需传customerCode
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/isAlertPageCheck")
    public String isAlertPageCheck(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        AlertPageCheckCommand command = JSON.parseObject(requestMsg.getData().toString(),AlertPageCheckCommand.class);
        command.setCtx(CommandContext.getContext());
        List<ContractManagerVo> list = contractAgreementManagerService.alertPageCheck(command); 
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("contractManagerVos", list);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    
    /**
     * 客户登录后 同意或拒绝签订合同/协议时应保存记录
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/signContract")
    public String signContract(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        SignContractCommand command = JSON.parseObject(requestMsg.getData().toString(),SignContractCommand.class);
        command.setCtx(CommandContext.getContext());
        contractAgreementManagerService.signContract(command); 
        return SUCCESS;
    }
    
    @RequestMapping(value = "/signContractOrAgreement")
    public String signContractOrAgreement(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        SignContractCommand command = JSON.parseObject(requestMsg.getData().toString(),SignContractCommand.class);
        command.setCtx(CommandContext.getContext());
        contractAgreementManagerService.signContract(command); 
        return SUCCESS;
    }
    
    @RequestMapping(value = "/queryIspAndOwhs")
    public String queryIspAndOwhs(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        IdCommand command = JSON.parseObject(requestMsg.getData().toString(),IdCommand.class);
        
        List<Contract> contracts = umsCustomerService.queryContractsByCustomerId(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("contracts", contracts);
        responseMsg.setData(data);
        return SUCCESS;  
    }
    
    /**
     * 
     *通过客户编码批量校验用户是否存在 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/checkCustomerCode")
    public String checkCustomerCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        CheckCodeCommand command = JSON.parseObject(requestMsg.getData().toString(),CheckCodeCommand.class);        
        List<CompanyVo> companyVos = umsCustomerService.checkCustomerCode(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("companyVos", companyVos);
        responseMsg.setData(data);
        return SUCCESS;   
    }
    
    /**
     * 
     *查询所有客户
     * @param requestMsg
     * @param responseMsg
     * @return list
     */
    @RequestMapping(value = "/queryAllCustomer")
    public String queryAllCustomer(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        CustomerQueryCommand command = JSON.parseObject(requestMsg.getData().toString(),CustomerQueryCommand.class);        
        List<CompanyVo> companyVos = umsCustomerService.queryAllCustomer(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("companyVos", companyVos);
        responseMsg.setData(data);
        return SUCCESS;   
    }
    
    /**
     * 
     *查询所有客户
     * @param requestMsg
     * @param responseMsg
     * @return list
     */
    @RequestMapping(value = "/isOpenAgreement")
    public String isOpenAgreement(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	QueryCustomerAgreementByTypeAndCustomerCode command = JSON.parseObject(requestMsg.getData().toString(),QueryCustomerAgreementByTypeAndCustomerCode.class);        
        Boolean bool = contractAgreementManagerService.isOpenAgreement(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("isOpenAgreement", bool);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    
    /**
     * 根据客户编码查询有效直发白名单(汇中，不同仓库合并)
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/IsOpenDirectShipmentWhitelist")
    public String IsOpenDirectShipmentWhitelist(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	QueryDswByCustomerCodeCommand command = JSON.parseObject(requestMsg.getData().toString(),QueryDswByCustomerCodeCommand.class);        
    	DirectShipmentWhitelistVo returnVo = directShipmentWhitelistService.queryDirectShipmentWhitelist(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("directShipmentWhitelist", returnVo);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 根据客户编码，开通白名单类型（直发国内，直发海外，自验）查询直发白名单详情
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryDirectShipmentWhitelist")
    public String queryDirectShipmentWhitelist(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	GetDirectShipmentWhitelistCommand command = JSON.parseObject(requestMsg.getData().toString(),GetDirectShipmentWhitelistCommand.class);        
    	List<DirectShipmentWhitelistVo> returnList = directShipmentWhitelistService.getDirectShipmentWhitelist(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("directShipmentWhitelistList", returnList);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 根据客户编码，订单类型判断客户是否开通协议  
     * 直发国内验/直发海外验--》查询卖家头程直发协议是否签署
     * 自验货（或直发国内验&自验）--》查询卖家头程直发协议，卖家自验货承诺书，自验货checkList签署
     * 直发国内：DI   直发海外：DW   自验：SF
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/customerIsOpenAgreementForDsw")
    public String customerIsOpenAgreementForDsw(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	CustomerIsOpenAgreementForDsw command = JSON.parseObject(requestMsg.getData().toString(),CustomerIsOpenAgreementForDsw.class);
    	Map<String, Object> data = new HashMap<String, Object>();
    	if("SF".equals(command.getOrderType())){
    		QueryCustomerAgreementByTypeAndCustomerCode isOpenCommand = new QueryCustomerAgreementByTypeAndCustomerCode(); 
    		//自验货CHECKLIST
    		isOpenCommand.setCustomerCode(command.getCustomerCode());
    		isOpenCommand.setAgreementType("CSI_CHECKLIST");
            Boolean csiChecklistbool = contractAgreementManagerService.isOpenAgreement(isOpenCommand);
            if(!csiChecklistbool){
            	ServiceTypeVo serviceTypeVo = contractAgreementManagerService.queryByCode("CSI_CHECKLIST");
            	data.put("CSI_CHECKLIST", serviceTypeVo.getRemark());
            }
            
            //自验承诺书
            isOpenCommand.setAgreementType("CSI_COMM");
            Boolean csiCommBool = contractAgreementManagerService.isOpenAgreement(isOpenCommand);
            if(!csiCommBool){
            	ServiceTypeVo serviceTypeVo = contractAgreementManagerService.queryByCode("CSI_COMM");
            	data.put("CSI_COMM", serviceTypeVo.getRemark());
            }
            //头程直发协议
            isOpenCommand.setAgreementType("SHR_SUPPLEMENTARY");
            Boolean shrSupplementaryBool = contractAgreementManagerService.isOpenAgreement(isOpenCommand);
            if(!shrSupplementaryBool){
            	ServiceTypeVo serviceTypeVo = contractAgreementManagerService.queryByCode("SHR_SUPPLEMENTARY");
            	data.put("SHR_SUPPLEMENTARY", serviceTypeVo.getRemark());
            }
    	}else{
    		//头程直发协议
    		QueryCustomerAgreementByTypeAndCustomerCode isOpenCommand = new QueryCustomerAgreementByTypeAndCustomerCode();  
    		isOpenCommand.setCustomerCode(command.getCustomerCode());
            isOpenCommand.setAgreementType("SHR_SUPPLEMENTARY");
            Boolean shrSupplementaryBool = contractAgreementManagerService.isOpenAgreement(isOpenCommand);
            if(!shrSupplementaryBool){
            	ServiceTypeVo serviceTypeVo = contractAgreementManagerService.queryByCode("SHR_SUPPLEMENTARY");
            	data.put("SHR_SUPPLEMENTARY", serviceTypeVo.getRemark());
            }
    	}
        responseMsg.setData(data);
        return SUCCESS;
    }

}
